import type { RouteRecordRaw, Router } from "vue-router";
import { usePermissionStoreWithout } from "@/stores/module/permission";
import { toRefs, markRaw } from "vue";
import Layout from "@/layout/Layout.vue";

const routeComponents = import.meta.glob("@/views/**/*.vue");

/** 转换为真正组件 */
export const convertComponent = (accessRoutes: RouteRecordRaw[]) => {
  const res: RouteRecordRaw[] = [];
  for (const item of accessRoutes) {
    // @ts-ignore
    const route = { ...item, component: item.component === "#" ? Layout : routeComponents[item.component] };
    if (item.children) {
      route.children = convertComponent(item.children);
    }
    // @ts-ignore
    res.push(route);
  }
  return res;
};

/** 路由拦截器中添加路由 */
let flag = false;
export const setupDynamicRoute = (router: Router) => {
  router.beforeEach((to, from, next) => {
    try {
      const { accessRoutes } = toRefs(usePermissionStoreWithout());
      const routes = convertComponent(accessRoutes.value);
      if (!flag) {
        // 后端返回的路由表
        routes.forEach((route) => {
          router.addRoute(route);
        });
        flag = true;
        // 这样处理是因为，第一次路由还未加载完成会会报警告 `No match found for location with path`
        // to.redirectedFrom 包含了重定向之前最初想访问的地址
        // 第一次访问路由尚未加载完成会重定向到404
        if (to.path === "/404" && to.redirectedFrom) {
          next({ path: to.redirectedFrom.fullPath, replace: true });
        } else {
          next({ ...to, replace: true }); //路由进行重定向放行
        }
      } else {
        next();
      }
    } catch (error) {}
  });
};

export const loginToAddRoutes = (router: Router) => {
  const { accessRoutes } = toRefs(usePermissionStoreWithout());
  const routes = convertComponent(accessRoutes.value);
  routes.forEach((route) => {
    router.addRoute(route);
  });
};
